package com.dayuanit.dy15.websocket.handler;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 处理websokset的消息
 */
public class AtmWebsocketHandler extends TextWebSocketHandler {

    //线程安全的Map集合  key=userId  value=websocketSession对象
    private static final Map<String, WebSocketSession> sessionMap = new ConcurrentHashMap<>();

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println(">>>>>>>>message=" + message);
    }

    /**
     * websocket建立连接后 调用的方法
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println(">>>>>>>>>>>>websocket建立连接" + session);

        session.sendMessage(new TextMessage("hello world form server"));

        //此userId 是在websocket拦截器中放进去的
        Object userId = session.getAttributes().get("userId");
        System.out.println(">>>>userId=" + userId);

        //将用户的WebSocketsession存放到Map集合中，以后若对某个用户发送消息，要通过用户的userID到集合中取对应的session对象然后发送消息。
        sessionMap.put(userId.toString(), session);
    }

    /**
     * 连接关闭后 将session移除map集合
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String userId = (String)session.getAttributes().get("userId");
        if (!sessionMap.containsKey(userId)) {
            return;
        }

        //如果连接断掉，则将对应的session对象从集合中删除。
        WebSocketSession webSocketSession = sessionMap.get(userId);
        if (webSocketSession != null && webSocketSession.isOpen()) {
            webSocketSession.close();
        }

        sessionMap.remove(userId);
    }

    /**
     * 给用户发送消息
     * @param userId
     * @param message
     */
    public void sendMessage(String userId, String message) {
        WebSocketSession webSocketSession = sessionMap.get(userId);
        try {
            webSocketSession.sendMessage(new TextMessage(message));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
